package dao;

import db.DBUtil;
import model.Employee;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 员工数据访问类，操作员工数据库
 */
public class EmployeeDAO {
    
    /**
     * 注册新员工
     */
    public boolean registerEmployee(Employee employee) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO employees (employee_id, name, position, salary, phone, password) " +
                         "VALUES (?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, employee.getEmployeeId());
            pstmt.setString(2, employee.getName());
            pstmt.setString(3, employee.getPosition());
            pstmt.setDouble(4, employee.getSalary());
            pstmt.setString(5, employee.getPhone());
            pstmt.setString(6, employee.getPassword());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("注册员工失败: " + e.getMessage());
            return false;
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                DBUtil.closeConnection(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 根据ID和密码登录
     */
    public Employee login(String employeeId, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Employee employee = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM employees WHERE employee_id = ? AND password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, employeeId);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getString("employee_id"));
                employee.setName(rs.getString("name"));
                employee.setPosition(rs.getString("position"));
                employee.setSalary(rs.getDouble("salary"));
                employee.setPhone(rs.getString("phone"));
                employee.setPassword(rs.getString("password"));
            }
        } catch (SQLException e) {
            System.err.println("员工登录查询失败: " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                DBUtil.closeConnection(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        return employee;
    }
}
    